from rest_framework import serializers

from goods.models import SKU


class CartSerializers(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    def validate(self, attrs):
        # 验证sku_id是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在!')

        # 验证商品库存
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('商品库存不足！')

        return attrs


class CartsSerializers(serializers.ModelSerializer):
    count = serializers.IntegerField(read_only=True)
    selected = serializers.BooleanField(read_only=True)

    class Meta:
        model = SKU
        fields = '__all__'


class CartDeleteSerializers(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):
        # 验证sku_id是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在!')

        return attrs


class CartSelectionSerializers(serializers.Serializer):
    selected = serializers.BooleanField(write_only=True)